package com.atguigu.gulimall.ware.dao;

import com.atguigu.gulimall.ware.entity.WareSkuEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

/**
 * 商品库存
 *
 * @author leifengyang
 * @email leifengyang@gmail.com
 * @date 2019-10-08 09:59:40
 */
@Mapper
public interface WareSkuDao extends BaseMapper<WareSkuEntity> {

    void addStock(@Param("skuId") Long skuId, @Param("wareId") Long wareId, @Param("skuNum") Integer skuNum);

    @Select("SELECT SUM(stock-stock_locked) FROM wms_ware_sku WHERE sku_id =#{skuId}")
    Long getSkuStock(@Param("skuId") Long skuId);

    /**
     * 查询skuId所有仓库信息
     * @param skuId
     * @return
     */
    @Select("SELECT ware_id FROM wms_ware_sku WHERE sku_id=#{skuId} AND stock-stock_locked>0")
    List<Long> listWareIdHasSkuStock(@Param("skuId") Long skuId);

    /**
     * 锁定库存
     * @param skuId
     * @param wareId
     * @param num
     * @return
     */
    @Update("UPDATE wms_ware_sku SET stock_locked = stock_locked+#{num} WHERE sku_id=#{skuId} AND ware_id=#{wareId} AND stock-stock_locked>=#{num}")
    Long lockSkuStock(@Param("skuId") Long skuId, @Param("wareId") Long wareId, @Param("num") Integer num);

    /**
     * 释放库存
     * @param skuId
     * @param wareId
     * @param num
     */
    @Update("UPDATE wms_ware_sku SET stock_locked=stock_locked-#{num} WHERE sku_id = #{skuId} AND ware_id = #{wareId}")
    void unLockStock(@Param("skuId") Long skuId, @Param("wareId") Long wareId, @Param("num") Integer num);
}
